
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#include <unistd.h>

#include "wifi_data.h"
#include "ipc_msg.h"
#include "get_wifi_ap.h"

#define WIFI_ADVERISEMENT_NSGTYPE 0x00000001
#define WIFI_ADVERISEMENT_KEY 0x00000001

struct wifi_adi
{
    long m_type;
    long len;
    char m_text[1500];
};

static int msgid = 0;

static void *wifi_data_dispose(void *arg)
{
    msgid = open_msg_queue(WIFI_ADVERISEMENT_KEY);
    if (msgid == -1)
    {
        printf("error\n");
        return NULL;
    }

    struct wifi_adi wdata;

    while (1)
    {
        memset(&wdata, 0, sizeof(struct wifi_adi));
        wdata.len = 1500;

        recv_msg_from_queue(msgid, WIFI_ADVERISEMENT_NSGTYPE, &wdata);

        //printf("%ld\n%s\n", wdata.len, wdata.m_text);

        wifi_data_list_t list;
        list.len = wdata.len / 50;
        list.wifi_data_list = (wifi_data_t *)malloc(sizeof(wifi_data_t) * list.len);
        memset(list.wifi_data_list, 0, sizeof(wifi_data_t) * list.len);

        int i = 0;
        char tmp[50];
        for (; i < list.len; ++i)
        {
            memcpy(tmp, wdata.m_text + i * 50, 50);
            sscanf(tmp, "%[^|]|%[^|]|%*[^|]|%*[^|]|%*[^|]|%d[^\r]",
                   list.wifi_data_list[i].src_mac, list.wifi_data_list[i].dst_mac, &(list.wifi_data_list[i].rssi));

            //printf("list\t %s %s %d\n", list.wifi_data_list[i].src_mac, list.wifi_data_list[i].dst_mac, list.wifi_data_list[i].rssi);
        }

        wifi_data_add_sta(&list);

        free(list.wifi_data_list);
        list.wifi_data_list = NULL;
    }
}

static void pthread_wifi_data_dispose()
{
    pthread_t tid;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_create(&tid, &attr, wifi_data_dispose, NULL);
}

static void *wifi_data_wifiAP(void *arg)
{
    while (1)
    {
        WIFI_AP_INFO_LIST *list = softap_get_scan_res();
        if (list != NULL)
        {
            wifi_data_add_ap(list);
            softap_apinfo_free(list);
        }

        sleep(5);
    }

    return NULL;
}

static void pthread_wifi_data_wifiAP()
{
    pthread_t tid;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_create(&tid, &attr, wifi_data_wifiAP, NULL);
}

int main()
{

    pthread_wifi_data_dispose();
    pthread_wifi_data_wifiAP();

    configs_init();
    configs_show();

    while (1)
    {
        sleep(10);

        wifi_data_get_report_data();
    }

    return 0;
}
